﻿<?xml version="1.0" ?>
<scxml xmlns="http://www.w3.org/2005/07/scxml" version="1.0" initial="root" profile="ecmascript" name="Phratris">
  <parallel id="root">
    <state id="ui" initial="UnauthenticatedUserState">

      <!--sub state Unauthenicated-->
      <state id="UnauthenticatedUserState">
        <onentry>
          <if cond="(_data.login === null) || (_data.login === undefined)">
            <script> 
              $('#refhome').show();
              _data.imagedemo = new ImageWidget('demo');
              _data.service = new WebService("../../Service1.asmx");
              _data.login = new LoginWidget("mylogin","",function(){raise('login');});
              _data.stath = new LinkSt("linkStat",function(){raise('statis');},"Statistics","Statistics");
              $('body').append(_data.stath.toString());
              with(_data){
                imagedemo.setPosition(20,10);
                imagedemo.setDimension(110,80);
                imagedemo.setUri('images/Phratris.png');
                imagedemo.render("body",true,'slow',true,'slow');
                //login.setDimension("center",20);
                login.setDimension(20,20);
                login.setPosition(67,30);
                login.setDrag(true);
                login.setBackgroundImg("images/login.png");
                login.appendText("please [[register]]",new LinkSt("linkId",function(){raise("register");},"link_class","register"));
                login.render();
              } 
            </script>
          <else/>
            <script>
              $('#refhome').show();
              $('body').append(_data.stath.toString());
              _data.imagedemo.render();
              _data.login.render();
              _data.login.showMe();
            </script>
          </if>
        </onentry>
        <onexit>
          <script>
            $('#linkStat').remove();
            _data.imagedemo.deleteMe();
            _data.login.deleteMe();
          </script>
        </onexit>
        <transition event="login" target="LoginConnection" />
        <transition event="statis" target="DrawStat" />
        <transition event="register" target="RegistrationState" />
      </state>
      
      <state id="DrawStat">
        <onentry>
          <script>
            $('#statistiche').show();
            //newwindow=window.open('Statistic/Charts.html','Utenti loggatti recentemente','menubar=0,toolbar=0,status=0,links=1');
            //if (window.focus) {newwindow.focus();}
            htmlS = '&lt;iframe id="Userhi" src ="Statistic/Charts.html" frameborder="0" scrolling="no" width="720px" height="465px"&gt;&lt;/iframe&gt;';
            $('#statistiche').html(htmlS);
            _data.myButtonBack1 = new ButtonWidget('Back1',function() { raise( 'home' ); });
            with(_data){
              myButtonBack1.setPosition(100,6);
              myButtonBack1.setInnerText('Back');
              myButtonBack1.render();
            }
          </script>
        </onentry>
        <onexit>
          <script>
            $('#Userhi').remove();
            $('#statistiche').hide();
            _data.myButtonBack1.deleteMe();
            delete _data.myButtonBack1;
          </script>
        </onexit>
        <transition event="home" target="UnauthenticatedUserState" />
      </state>

      <!-- connessione al web service -->
      <state id="LoginConnection">
        <onentry>
          <script>
            _data.logdatin = new loginData(_data.login.User,MD5(_data.login.Pass));
            _data.logdatout = new logoutData();
            try{
              with(_data){
                service.Login(logdatin,logdatout,function(){raise('feedBackLogin');});
              }              
            } 
            catch(error){
              if(error instanceof ConnectException)
                alert('Connection Error');
            }
          </script>
        </onentry>
        <transition event="feedBackLogin" target="feedBack" />
      </state>

      <!-- controllo callback comunicazione server -->
      <state id="feedBack">
        <onentry>
          <script>
            if(_data.logdatout.connectionSuccess == true){
              if(_data.logdatout.logged === 'true'){
                alert('You are already logged in as: '+_data.logdatout.userid);
              }
              raise('positive');
            }else {
              alert('Forgot your Username?');
              raise('negative');
            }
          </script>
        </onentry>
        <transition event="negative" target="UnauthenticatedUserState" />
        <transition event="positive" target="istruzioni" >
          <script>
            _data.login.deleteMe();
            _data.imagedemo.deleteMe();
            delete _data.imagedemo;
            delete _data.login;
          </script>
        </transition>
      </state>

      <!-- sub state Registration -->
      <state id="RegistrationState" initial="modulo">
        <!-- eseguita all'ingresso dello stato -->
        <onentry>
          <script>
            _data.myButtonBack = new ButtonWidget('Back',function() { raise( 'back' ); });
            with(_data){             
              myButtonBack.setPosition(5,6);
              myButtonBack.setInnerText('Back');
              myButtonBack.render();
            }
          </script>
        </onentry>

        <!--State for registration account-->
        <state id="modulo">
          <onentry>
            <script>
              prepareField();
              
              function validatePass(id){
                if($('#'+id).val().length &lt; 6)
                  return 'la password deve avere almeno 6 caratteri';
                else return 'Ok';
              }

              function checkPass(){
                var pas1 = document.getElementById('registration_pass_pass').value;
                var pas2 = document.getElementById('registration_repass_pass').value;
                if(pas1 === pas2){
                  return 'Ok';
                }
                else
                  return 'Password non corrispondente';
              }

              function validateEmail() {
                var email = document.getElementById('registration_email_input');
                var filter = /^([a-zA-Z0-9_.-])+@(([a-zA-Z0-9-])+.)+([a-zA-Z0-9]{2,4})+$/;
                if (!filter.test(email.value)) {
                  alert('Please provide a valid email address');
                  return 'email inserita non valida';
                }
                return 'Ok';
              }

              function checkEmail(){
                var em1 = document.getElementById('registration_email_input').value;
                var em2 = document.getElementById('registration_remail_input').value;
                if(em1 === em2){
                  return 'Ok';
                }
                else {
                  return 'Email non corrispondente';
                }
              }
              _data.asd = new RegisterWidget("registration",function(){raise('submit');});
              with(_data){                
                asd.addField("nick", "Nickname", {type:"input", mandatory:true});
                asd.addField("pass", "Password", {type: "pass", mandatory:true, validator:validatePass });
                asd.addField("repass", "Conferma Password", {type:"pass", mandatory:true, validator:checkPass });
                asd.addField("email", "E-mail", {type:"input", mandatory:true, validator:validateEmail });
                asd.addField("remail", "Conferma E-mail", {type:"input", mandatory:true, validator:checkEmail });
                asd.addField("data", "Data di nascita", {type:"date", end: "+3m+2w-1d", show:'13/02/1997', start: null});   		
                asd.addField("hobby", "Interessi", {type:"drop", mandatory:false, options:{1:"Informatica", 2:"Letteratura", 3:"Lingue", 4:"Altro" }});
                asd.render("game_area");
              }
              _data.sos = new HelpWidget("nckhlp", {content:"Inserisci un nickname valido di almeno 6 caratteri", button:"help", attach:"registration_nick label"});
              _data.sos.render();
            </script>
          </onentry>
          <transition event="submit" target="Registration" />
        </state>

        <!--state with call the web method registrer-->
        <state id="Registration">
          <onentry>
            <script>
              try{
                _data.regdataout = new Object();
                var nick = document.getElementById('registration_nick_input');
                var pass = document.getElementById('registration_pass_pass');
                var email = document.getElementById('registration_email_input');
                var msg = new messageRegister(nick.value,nick.value,nick.value,email.value,MD5(pass.value));
                _data.service.Register(msg,_data.regdataout,function(){raise('info');});
              }
              catch(e){
                if(e instanceof ConnectException)
                  alert('Connection Error '+e.toString());//fai raise
              }
            </script>
          </onentry>          
          <transition event="info" target="Info" />
        </state>

        <!--state view the information again the account-->
        <state id="Info">
          <onentry>
            <script>
              _data.myRegistration = new TextWidget("info");
              with(_data){
                if(regdataout.risposta == 'true'){
                  asd.deleteMe();
                  delete _data.asd;
                  myRegistration.setDimension(100,30);
                  myRegistration.setPosition(5,3);
                  myRegistration.setFont(20);
                  myRegistration.setInnerText('Complimenti ti sei registrato. Ora puoi giocare.');
                  myRegistration.render("game_area");
                  setTimeout(function(){raise('log');},2000);
                }
                else{
                  //alert(regdataout.msg);
                  if(regdataout.msg === 'user')
                    _data.asd.verify({'registration_nick_input': 'Il nickname scelto non è disponibile. Cambialo!'});
                  else if (regdataout.msg === 'email')
                    _data.asd.verify({'registration_email_input': 'E-mail gia registrata. Cambiala!'});
                  
                }
              }
            </script>
          </onentry>
          <onexit>
            <script>
              _data.myRegistration.deleteMe();
              delete _data.myRegistration; 
            </script>
          </onexit>
          <transition event="submit" target="Registration" />
          <transition event="log" target="UnauthenticatedUserState" >
            <script>              
              _data.sos.deleteMe();
              delete _data.sos;
              _data.myButtonBack.deleteMe();
              delete _data.myButtonBack;
              $("#game_area").empty();
              $("#game_area").hide();
            </script>
          </transition>
        </state>

       <!--transizione per tornare alla pagina login -->
       <transition event="back" target="UnauthenticatedUserState">
          <script>
            _data.asd.deleteMe();
            delete _data.asd;
            _data.sos.deleteMe();
            delete _data.sos;
            _data.myButtonBack.deleteMe();
            delete _data.myButtonBack;
            $("#game_area").empty();
            $("#game_area").hide();
          </script>
        </transition>
      </state>

      <!-- immagine -->
      <state id="istruzioni">
        <onentry>
          <script>
            $('#refhome').hide();
            _data.loading = new TextWidget('ling');
            _data.loading.setInnerText('Loading...');
            _data.loading.setFont(30,'bolt');
            _data.loading.setColor('#000000');
            _data.loading.setPosition(65,5);
            _data.istr = new ImageWidget('istr');
            _data.istr.setPosition(20,10);
            _data.istr.setDimension(110,80);
            _data.istr.setUri("images/PhratrisIstruzioni.png");
            _data.istr.render();
            _data.loading.render();
            setTimeout(function(){raise('start');},10000);
          </script>
        </onentry>
        <onexit>
          <script>
            _data.loading.deleteMe();
            _data.istr.deleteMe();
            delete _data.loading;
            delete _data.istr;
          </script>
        </onexit>
        <transition event="start" target="Phrase_Game" />
      </state>
      
      <!--super-state first frame-->
      <state id="Phrase_Game" initial="Game">
        <datamodel>
          <data id="gamename" expr="'Phratris'" />
          <data id="punteggio" expr="0" />
        </datamodel>
        
        <!-- inizializzaione oggetti -->
        <onentry>
          <assign location="_data.dataout" expr="new messageAnswer()" />
          <script>
            try{
              with(_data){
                var bool = false;
                service.setAsync(bool);
                service.GetScore(gamename,dataout);
                bool = true;
                service.setAsync(bool);
              }            
            }
            catch(e){
              if(e instanceof ConnectException)
                alert('Connection Error '+e);//fai raise
              if(e instanceof IllegalArgumentException)
                alert('Invalid argument'+e);
            }            
            
            _data.buttonLogout = new ButtonWidget('logout',
              function() {
                try{
                  _data.service.Logout();
                } catch(e) {
                  if(e instanceof ConnectException)
                    alert('Connection Error '+ e);
                }
                raise('logout');
              });
            with(_data){
              buttonLogout.setInnerText('Logout');
              buttonLogout.setPosition(5,30);
              buttonLogout.setDimension(10,5);
              //buttonLogout.render();
            }
            
            _data.buttonStop = new ButtonWidget('Stop',
              function() {
                raise('StopGame');
              });
            with(_data){
              buttonStop.setInnerText('Stop');
              buttonStop.setPosition(5,30);
              buttonStop.setDimension(10,5);
              //buttonStop.render();
            }
            
            prepareField();
            _data.mySfondo = new ImageWidget("sfondo");
            with(_data){
              mySfondo.DIM_GRIGLIA = 1;
              mySfondo.setPosition(1,1);
              mySfondo.setDimension(851,551);
              mySfondo.setPadding(0);
              mySfondo.setDeepLevel(0);
              mySfondo.setUri('images/sfondoP2.png');
              mySfondo.render('game_area');
            }
            
            _data.minatore = new ImageWidget('mina');
            with(_data){
              minatore.DIM_GRIGLIA = 1;
              minatore.setPosition(1,1);
              minatore.setDeepLevel(3);
              minatore.setDimension(847,548);
              minatore.setUri("images/minatore_foglio.png");
              minatore.render('game_area');
            }
            
            _data.user = new TextWidget("User");
            with(_data){
              user.setPosition(0,55);
              user.setDimension(15,15);
              user.setDeepLevel(5);
              user.setBackground(0,"images/user.png");
              var acapo = '&lt;br /&gt;&lt;br /&gt;';
              var cl = '&lt;center&gt;';
              var cr = '&lt;/center&gt;';
              user.setInnerText(acapo+cl+logdatin.nickname.toString()+cr);
              user.setFont(20,'bold');
              user.setColor('#FFFFFF');
              user.render('game_area');
            }
            _data.punteggio = _data.dataout.score;
            _data.scoreT = new TextWidget("scoreT");
            with(_data){
              scoreT.setPosition(20,55);
              scoreT.setDeepLevel(5);
              scoreT.setDimension(15,15);
              scoreT.setBackground(0,"images/tesoro.png");
              var spazzi = '&lt;br /&gt;';
              var cl = '&lt;strong&gt;&lt;center&gt;';
              var cr = '&lt;/center&gt;&lt;/strong&gt;';
              scoreT.setInnerText(spazzi+cl+dataout.score+cr);
              scoreT.setFont(20,'bolt');
              scoreT.setColor('#000000');
              scoreT.render('game_area');
            }  
            //precarica immagini animazione
            _data.imageLoad = new Array('images/Dinamite3.png','images/Dinamite2.png','images/Dinamite1.png','images/Dinamitego.png');  
            if (document.images){
              document.wl = new Array();
              for (var i = 0; i &lt; 4; i++) {
                document.wl[i] = new Image();
                document.wl[i].src = _data.imageLoad[i];
              }
            }
          </script>
        </onentry>

        <!--spiegazione game-->
        <state id="Game">
          <onentry>
            <!-- creo Bottone Start, e descrizione Descr -->
            <script>
              _data.buttonStop.deleteMe();
              _data.buttonLogout.render();
              _data.StartGame = new ButtonWidget('sng',function() {
                  raise( 'startgame' );
                });
              with(_data){             
                StartGame.setPosition(47,16);
                StartGame.setInnerText('Start new Game');
                StartGame.setDeepLevel(4);
                StartGame.render('game_area');
              }
              
              _data.Descr = new TextWidget("descrizione");
              with(_data){                
                Descr.setDimension(30,3);
                Descr.setDeepLevel(6);
                Descr.setPosition(41,8);
                Descr.setFont(34,'bold');
                var cl = '&lt;label&gt;'
                var cr = '&lt;/label&gt;';
                Descr.setInnerText(cl+'Phratris '+cr);
                Descr.render('game_area');
              }
              
              _data.helpPhratris = new HelpWidget("hlphra", {content:"Al cadere dei massi, muovi il treno e trova il giusto carrello", button:"Demo", attach:"descrizione label"});
              _data.helpPhratris.setDeepLevel(6);
              _data.helpPhratris.render();
            </script>
          </onentry>
          <onexit>
            <!-- libero i widget StartGame,Descr-->
            <script>
              with(_data){
                helpPhratris.deleteMe();
                delete helpPhratris;
                StartGame.deleteMe();
                delete StartGame;
                Descr.deleteMe();
                delete Descr;
                buttonStop.render();
                buttonLogout.deleteMe();
              }
            </script>
          </onexit>
          <transition event="startgame" target="StartGame" />
        </state>
        
        
        <!-- comunicazione get question -->
        <state id="StartGame">
          <datamodel>
            <data id="load" expr="0" />            
          </datamodel>
          <onentry>
            <assign location="_data.datout" expr="new messageQuestion()"></assign>
            <script>                           
              //_data.imgL = new TextWidget('imgload');
              _data.imgL = new ImageWidget('imgload');
              _data.imgL.setPosition(37,18);
              _data.imgL.setDimension(30,30);
              _data.imgL.setUri(_data.imageLoad[0]);
              //_data.imgL.setBackground(0,_data.imageLoad[0]);
              _data.imgL.render('game_area');
              _data.strFunctio = function(){
                _data.load = (_data.load+1) % 4;
                if(_data.load == 3){ setTimeout(function(){raise('game');},1000); }
                //_data.imgL.setBackground(0,_data.imageLoad[_data.load]);
                _data.imgL.setUri(_data.imageLoad[_data.load]);
                _data.imgL.render('game_area');
              };
              var inl = window.setInterval('document.statechart._data.strFunctio()', 2000 );
              _data.intral = inl;              
              var dati = ''+_data.gamename;
              _data.service.GetQuestion(dati,_data.datout,function(){raise('callback');});
            </script>            
          </onentry>          
          <transition event="callback" target="loadingEnd" />
        </state>

        <state id="loadingEnd">          
          <transition event="game" target="validateTermination" >
            <script>
              clearInterval(_data.intral);
              _data.imgL.deleteMe();              
            </script>
          </transition>
        </state>
        
        <state id="validateTermination" >          
          <transition cond="_data.datout.gameover != undefined &amp;&amp; _data.datout.gameover" target="GameOver" />
          <transition target="CreateData" />
        </state>

        <state id="GameOver">
          <onentry>
            <script>
              _data.msgGameOver = new TextWidget('gameoev');
              _data.rigioca = new ButtonWidget('rigioca',function(){raise('rigioca')});
              with(_data){
                msgGameOver.setInnerText('Game Over');
                msgGameOver.setPosition(41,8);
                msgGameOver.setDeepLevel(6);
                msgGameOver.setDimension(30,3);
                msgGameOver.setFont(34,'bold');
                msgGameOver.render('game_area');
                rigioca.setInnerText('Rigioca');
                rigioca.setPosition(50,20);
                rigioca.setDeepLevel(6);
                rigioca.render('game_area');
              }
            </script>
          </onentry>
          <onexit>
            <script>
              _data.msgGameOver.deleteMe();
              delete _data.msgGameOver;
              _data.rigioca.deleteMe();
              delete _data.rigioca;
            </script>
          </onexit>
          <transition event="rigioca" target="StartGame" >
            <script>
              var spazzi = '&lt;br /&gt;';
              var cl = '&lt;strong&gt;&lt;center&gt;';
              var cr = '&lt;/center&gt;&lt;/strong&gt;';
              _data.punteggio = 0;
              _data.scoreT.setInnerText(spazzi+cl+'0'+cr);
              $("#" + "scoreT").html(''+spazzi+cl+'0'+cr);
            </script>
          </transition>
        </state>

        <!-- prima volta costruisco la struttura dati -->
        <state id="CreateData">
          <onentry>
            <!-- indice di part of speech -->
            <assign location="_data.pos" expr="0" />
            <!-- indice albero semantico-->
            <assign location="_data.itertree" expr="1" />
            <!-- indice nodo albero -->
            <assign location="_data.iternode" expr="0" />
            <!-- array[metacarattere]=caratteri in nomi -->
            <assign location="_data.POS" />
            <!-- indice struttura dati -->
            <assign location="_data.index" />
            <!-- struttura dati array multidimenzionale [pos,tree_1,,tree_9][pos[],nodi0[],,nodi9[]]-->
            <assign location="_data.struct" />
            <!-- controllo del tipo di dato(number)>pos (string)>attachment -->
            <assign location="_data.controllo" />
            <!-- controllo terminazione -->
            <assign location="_data.end" />
            <!-- array sas -->
            <!--assign location="_data.gold" exrp="new Array();"/-->
            <!-- array carelli -->
            <assign location="_data.treno" expr="new Array();"/>
            <script>
              //document.midi.Play();
              _data.gold = new Array();
              _data.sublist =  new ListBox("listbox",null,"Sottofrasi");
              _data.POS = {              
                'A' :	'adjective',
                'B' :	'adverb',
                'C' :	'conjunction',
                'D' :	'determiner',
                'E' :	'preposition',
                'F' :	'punctuation',
                'I' :	'interjection',
                'N' :	'numeral',
                'P' :	'pronoun',
                'R' :	'article',
                'S' :	'noun',
                'T' :	'predeterminer',
                'V' :	'verb',
                'X' :	'residual class'
              };
              _data.index = [
                'partofspeech',
                'tree_0',
                'tree_1',
                'tree_2',
                'tree_3',
                'tree_4',
                'tree_5',
                'tree_6',
                'tree_7',
                'tree_8',
                'tree_9'
              ];
              
              _data.struct = new Iter(_data.datout.subclass); 
              _data.conteiner = new TextWidget('box');
              _data.conteiner.setDeepLevel(2);
              _data.anim_conteiner = new Animation(_data.conteiner);
              _data.bilance = 0;
              _data.num_parole_sx = -3;
              _data.num_parole_dx = _data.struct[_data.index[_data.pos]].length - 4;
              var keyl = function(){if(_data.bilance &lt; _data.num_parole_dx){_data.bilance++; _data.anim_conteiner.setCss({"left" : "-=112"}); _data.anim_conteiner.animate_w(false);}};
              var keyr = function(){if(_data.bilance &gt; _data.num_parole_sx){_data.bilance--; _data.anim_conteiner.setCss({"left" : "+=112"}); _data.anim_conteiner.animate_w(false);}};
              
              function checkKey(e){
                 switch (e.keyCode) {
                      case 40:
                          //alert('down');
                          break;
                      case 38:
                          //alert('up');
                          break;
                      case 37:
                          //alert('left');
                          keyl();
                          break;
                      case 39:
                          //alert('right');
                          keyr();
                          break;
                      default:
                          //alert('tasto non usato');  
                          }      
              }
              if ($.browser.mozilla) {
                  //$(document).bind ('keypress',checkKey);
                  $(document).keypress (checkKey);
              } else {
                  $(document).keydown (checkKey);
                  //$(document).bind ('keydown',checkKey);
              } 
               
              with(_data){
                //struct = new Iter(datout.subclass); 
                //for per i carrelli
                var arPos = struct[index[pos]];
                var iter = IteratorArray(arPos);
                var idx = 0;
                var x = 5;
                var contX = (15*arPos.length)+5;
                conteiner.setPosition(2,36);
                conteiner.setDimension(contX,16);
                conteiner.render('game_area');
                var capo = '&lt;br/&gt;';
                var cl = '&lt;strong&gt;&lt;center&gt;';
                var cr = '&lt;/center&gt;&lt;/strong&gt;';
                while(iter.hasNext()){
                  var item = iter.next();
                  //creazione treno
                  var parola = POS[(item.value)[1]];
                  var tcarrello = new TextWidget("carrello"+idx);
                  idx++;
                  tcarrello.setPosition(x,2);
                  x += 13;
                  tcarrello.setDimension(13,10);
                  tcarrello.setBackground(0,"images/carrello.png");
                  tcarrello.setInnerText(capo+cl+parola+cr);
                  tcarrello.setFont(17);
                  //manca il font-family css
                  //tcarrello.setFont(17,'normal','Nightclub BTN');
                  //tcarrello.setColor('#FF0000');
                  tcarrello.setPositionType('');
                  tcarrello.setFloat('left');
                  tcarrello.setDeepLevel(2);
                  tcarrello.render('box');

                  treno.push(tcarrello);
                }                
                
                //list box
                sublist.setPosition(45,50);
                sublist.setDeepLevel(5);
                sublist.setFont(12);
                sublist.setDimension(40,30);  
                sublist.render('game_area');
              }

              //with(_data){
              //struct = new Iter(datout.subclass);
              //for(var tr in struct){
              //  alert(tr+' '+struct[tr]);
              //}
              //alert('pos'+struct[index[pos]]);
              //for(; itertree &lt; 10 ; itertree++){
                //  alert(index[itertree]+' '+struct[index[itertree]]);
                //  var t = struct[index[itertree]];
                //  //alert(t);
                //  for(; iternode &lt; t.length; iternode++ ){
                //    alert(t[iternode]+' type '+typeof(t[iternode]));
                //  }
                //  iternode = 0;
                //}
              //}
            </script>
            <send event="callback" target="StartGame" />
          </onentry>
          <transition event="callback" target="GamePlay" />
        </state>  
        
        <!-- conrollo ramo if-->
        <state id="GamePlay">
          <onentry>
            <script>
              with(_data){
                controllo = typeof(struct[index[itertree]][iternode]);
                var t = struct[index[itertree]];                
                //alert('tipo nodo analizzato:'+controllo); 
                end = ((iternode == t.length)||(itertree == 10));
                //alert('fine gioco:'+end);
              }
            </script>
            <if cond="!(_data.end)" >
              <if cond="_data.controllo == 'number'">
                <send event="partofspeech" target="GamePlay" />
              <elseif cond="_data.controllo == 'string'" />
                <send event="attachment" target="GamePlay" />              
              </if>
            <else />
              <assign location="_data.dat_id" expr="_data.itertree" />
              <send event="final" target="GamePlay" />
            </if>
          </onentry>
          <transition event="partofspeech" target="PartOfSpeech" />
          <transition event="attachment" target="Attachment"/>
          <transition event="final" target="Final">
            <script>
              _data.conteiner.deleteMe();
            </script>
          </transition>
        </state>        
        
        <!-- animazione parola-->
        <state id="PartOfSpeech">          
          <onentry>
            <script>
              _data.flagstop = true;
              //alert('stato POS');              
              with(_data){
                var indice = struct[index[itertree]][iternode];
                var pair = struct[index[pos]][indice-1];
                var parola = pair[0];
                var tag = POS[pair[1]];
                //alert('indice:'+indice+' copia:'+parola+' POS '+tag);
                var cl = '&lt;b&gt;';
                
                var sassotemp = new TextWidget("sasso"+iternode);
                sassotemp.setPosition(47,3);
                sassotemp.setDimension(10,10);
                sassotemp.setBackground(0,"images/sasso.png");
                sassotemp.setDeepLevel(1);
                //var spazio = '&lt;br /&gt;';
                var cl = '&lt;center&gt;';
                var cr = '&lt;/center&gt;';
                sassotemp.setInnerText(cl+parola+cr);
                sassotemp.setFont(20);
                sassotemp.setColor('#FFAA00');
                sassotemp.setFloat('');
                sassotemp.render('game_area');
                
                var anim_sasso = new Animation(sassotemp);
                anim_sasso.setComplete(function(){raise('validate');});
                anim_sasso.setCss({"top": "290"});
                anim_sasso.setDuration(6500);
                //anim_sasso.setStep(function(){if(flagstop) return true; else return false;});
                //$('#sasso'+iternode).stop(); elimina il setInterval
                anim_sasso.setContainerList(treno);
                anim_sasso.setContainerPercentage(35,001);
                setTimeout(function(){anim_sasso.animate_w(true);},1000);                                            
              }
              _data.a = anim_sasso;
            </script>
          </onentry>
          
          <transition event="validate" target="validatePOS" />
        </state>

        <state id="validatePOS">
          <onentry>
            <assign location="_data.sas"  />
            <script> 
              with(_data){
                var val_index = struct[index[itertree]][iternode]-1;
                sas = new TextWidget('sasso_v'+val_index);
                gold.push(sas);
                sas.setDimension(10,5);
                sas.setDeepLevel(0);
                sas.setFont(20);
                sas.setColor('#A35B14');
                sas.setInnerText(a.obj.innertext);
                if((a.result != null)) {
                  a.obj.hideMe();
                  //alert('result:'+a.result+' = carrello'+val_index);
                  if(a.result == ("carrello" + val_index)) {
                    var x = (14*val_index)+3;
                    sas.setPosition(x,-6);
                    sas.setBackground(0,"images/sasso_ok.png" ); 
                    //alert("carrello"+val_index);
                    sas.render("carrello"+val_index);
                    setTimeout(function(){raise('ok');},2000);
                  }
                  else {//problema stringhe maggiori di 9
                    var alternative = parseInt(a.result.toString().substring(8,a.result.length));                    
                    //var subiternode = parseInt(a.result.toString().substring(a.result.length-1,a.result.length));
                    var x = (14*alternative)+3;
                    sas.setPosition(x,-6);
                    sas.setBackground(0, "images/sasso_ko.png" ); 
                    sas.render(a.result);
                    setTimeout(function(){raise('ko');},2000);
                  }
                }
                else {
                  a.obj.setBackground(0,'images/sasso_nero.png');
                  var position =$("#"+a.obj.id).offset();
                  var diff = $('#game_area').offset();
                  position.left = (position.left - diff.left) / 8;
                  position.top = (position.top - diff.top)/8;
                  a.obj.setPosition(Math.round(position.left),Math.round(position.top));                  
                  a.obj.render('game_area');
                  setTimeout(function(){raise('ko');},2000);
                }                
              }
            </script>
          </onentry>
          <onexit>
            <script>
              with(_data){      
                a.obj.deleteMe();
              }
            </script>
          </onexit>
          <transition event="ok" target="GamePlay" >
            <assign location="_data.iternode" expr="_data.iternode+1" />
          </transition>
          <transition event="ko" target="GamePlay" >
            <script>
              _data.sas.deleteMe();
              delete _data.sas;
              _data.gold.pop();
            </script>
          </transition>
        </state>
        
        <!-- animazione frase -->
        <state id="Attachment"> 
          <onentry>
            <script>               
              //alert('stato Att');              
              with(_data){
                var frase = struct[index[itertree]][iternode];
                var img1 = new ImageSt('images/ok.png','','','itsok','itsok');
                var img2 = new ImageSt('images/ko.png','','','itsko','itsko');
                var mylink1 = new LinkSt('id_link1',
                  function(){
                      raise('okA'); 
                      $(".itsok").width(30);
                      $(".itsko").width(10);                    
                    },
                    img1);
                var mylink2 = new LinkSt("id_link2",function(){raise('koA'); },img2);
                sublist.addWord({txt:frase,add:[" [[]] [[]]",mylink1,mylink2]});
                sublist.render('game_area');
              }
            </script>
          </onentry>
          <transition event="okA" target="GamePlay" >
            <assign location="_data.iternode" expr="_data.iternode+1" />
          </transition>
          <transition event="koA" target="GamePlay" >                      
            <assign location="_data.itertree" expr="_data.itertree+1" />
            <script>
              var i = new Iter(_data.gold);
              for(var s in i){
                i[s].deleteMe();
              }
              _data.gold = new Array();
              _data.sublist.deleteMe();
              _data.sublist = new ListBox("listbox","Sottofrasi");  
              _data.sublist.setPosition(45,51);
              _data.sublist.setDeepLevel(5);
              _data.sublist.setFont(12);
              _data.sublist.setDimension(40,30); 
              _data.sublist.render('game_area');              
            </script>
            <assign location="_data.iternode" expr="0" />  
          </transition>
        </state>

        <!-- comunicazione CheckAnswer-->
        <state id="Final">
          <onentry>
            <script>
              //document.midi.Stop();
              //document.midi.Rewind();
              //alert('comunicazione con il server CheckAnswer risposta:'+_data.itertree);
              _data.ans = new messageAnswer();
              try{
                var fun = function(){raise('callback');};                
                var name = ''+_data.gamename;                
                var answer = ''+_data.itertree;
                _data.service.CheckAnswer(name,answer,_data.ans,fun);
              }
              catch(error){
                if(error instanceof ConnectionException)
                  alert('Connection Error');
              }
            </script>
          </onentry> 
          <transition event="callback" target ="StartAgain"/>
        </state>

        <!-- messaggio restart-->
        <state id="StartAgain">
          <onentry>
            <script>
              if ($.browser.mozilla) {
                $(document).unbind ('keypress');
              } else {
                $(document).unbind ('keydown');
              }
              
              _data.myButtonRestart = new ButtonWidget('restart',function() { raise( 'newgame' );});
              with(_data){
                myButtonRestart.setPosition(50,20);
                myButtonRestart.setInnerText('Continua');
                myButtonRestart.setDeepLevel(5);
                myButtonRestart.render('game_area');
                
                if(ans.score != undefined){
                  var spazzi = '&lt;br /&gt;';
                  var cl = '&lt;strong&gt;&lt;center&gt;';
                  var cr = '&lt;/center&gt;&lt;/strong&gt;';
                  punteggio += ans.score;
                  scoreT.setInnerText(spazzi+cl+punteggio+cr);
                  $("#" + "scoreT").html(''+spazzi+cl+punteggio+cr);
                }                
              }
            </script>
          </onentry>
          <onexit>
            <script>
              _data.myButtonRestart.deleteMe();
              delete _data.myButtonRestart;
            </script>
          </onexit>
          <transition event="newgame" target="StartGame"/>
       </state>      
        
        <onexit>
          <script>
            _data.mySfondo.deleteMe();
            delete _data.mySfondo;
            _data.minatore.deleteMe();
            delete _data.minatore;
            _data.buttonLogout.deleteMe();
            delete _data.buttonLogout;
            _data.buttonStop.deleteMe();
            delete _data.buttonStop;
            _data.user.deleteMe();
            delete _data.user;
            _data.scoreT.deleteMe();
            delete _data.scoreT;
          </script>
        </onexit>
		
		    <transition event="StopGame" target="Game">
			    <script>
			      $('#sasso'+_data.iternode).stop();
			      $('#box').stop();
			      clearInterval(_data.intral);
			      //midi.Stop();
			      //midi.Rewind();
			      if ($.browser.mozilla) {
				      $(document).unbind ('keypress');
			      } else {
				      $(document).unbind ('keydown');
			      }
			      $("#game_area").empty();
			    </script>
		    </transition>
		
		
      </state>	  
	  
      <!-- external transitions, available for each state -->
      <transition event="logout" target="UnauthenticatedUserState">
        <script>
          $('#sasso'+_data.iternode).stop();
          $('#box').stop();
          clearInterval(_data.intral);
          //midi.Stop();
          //midi.Rewind();
          if ($.browser.mozilla) {
            $(document).unbind ('keypress');
          } else {
            $(document).unbind ('keydown');
          }
          $("#game_area").empty(); 
          $("#game_area").hide();
        </script>
      </transition>
    </state>
  </parallel>
</scxml>
